﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace JwtApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public LoginController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public ActionResult Login()
        {
            var claims = new[] { new Claim("userId", "2333") };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: "weixin",
                audience: "my.com",
                claims: claims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: creds);

            var takenCode = new JwtSecurityTokenHandler().WriteToken(token);

            return new JsonResult(takenCode);
        }

        [Authorize]
        public string GetUsreId()
        {
            var auth = Request.Headers["Authorization"];

            var strToken = auth.ToString().Replace("Bearer ", "");

            var token = new JwtSecurityTokenHandler().ReadJwtToken(strToken);
            return token.Claims.FirstOrDefault(a => a.Type == "userid").ToString();
        }
    }
}